package com.alibaba.citrus.cr.unified.inventory.functions.consignmentOrder;

import com.alibaba.citrus.cr.unified.inventory.repository.ConsignmentOrderLineRepository;
import com.alibaba.citrus.cr.unified.inventory.repository.ConsignmentOrderRepository;
import com.alibaba.citrus.cr.common.util.SpringContextUtil;
import com.epoch.app.crunifiedinventory.sdo.ConsignmentOrderLineSDO;
import com.epoch.app.crunifiedinventory.sdo.ConsignmentOrderSDO;
import lombok.Data;

@Data
public class ConsignmentOrderEntity {

    private ConsignmentOrderSDO consignmentOrderSDO;

    private static ConsignmentOrderRepository consignmentOrderRepository;
    private static ConsignmentOrderLineRepository consignmentOrderLineRepository;

    static {
        consignmentOrderRepository = SpringContextUtil.getBean(ConsignmentOrderRepository.class);
        consignmentOrderLineRepository = SpringContextUtil.getBean(ConsignmentOrderLineRepository.class);
    }

    public static ConsignmentOrderEntity of(ConsignmentOrderSDO consignmentOrderSDO) {
        ConsignmentOrderEntity consignmentOrderEntity = new ConsignmentOrderEntity();
        consignmentOrderEntity.consignmentOrderSDO = consignmentOrderSDO;
        return consignmentOrderEntity;
    }

    public String create() {
        consignmentOrderSDO.setStatus(1);
        consignmentOrderSDO.setSyncVersion(0);
        String id = consignmentOrderRepository.create(consignmentOrderSDO);
        consignmentOrderSDO.setId(id);
        for (ConsignmentOrderLineSDO consignmentOrderLineSDO : consignmentOrderSDO.getConsignmentOrderLineSDOS()) {
            consignmentOrderLineSDO.setConsignmentOrderId(id);
            consignmentOrderLineSDO.setStatus(1);
            consignmentOrderLineSDO.setSyncVersion(0);
            consignmentOrderLineSDO.setId(consignmentOrderLineRepository.create(consignmentOrderLineSDO));
        }
        return id;
    }

    public Boolean delete() {
        consignmentOrderSDO.setStatus(0);
        consignmentOrderRepository.delete(consignmentOrderSDO);
        for (ConsignmentOrderLineSDO consignmentOrderLineSDO : consignmentOrderSDO.getConsignmentOrderLineSDOS()) {
            consignmentOrderLineSDO.setStatus(0);
            consignmentOrderLineRepository.delete(consignmentOrderLineSDO);
        }
        return true;
    }
}
